package com.rabbitmq.rabbitmqextensions.listener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.rabbitmqextensions.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Slf4j
//@Component
public class RetryListener {

    /**
     * auto
     * @param message
     * @param channel
     * @throws IOException
     */
//    @RabbitListener(queues = Constants.RETRY_QUEUE)
//    public void listener(Message message) {
//        String messageInfo = new String(message.getBody());
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//
//        log.info("接收消息, message: {}, deliveryTag: {}", messageInfo, deliveryTag);
//
//        int num = 1 / 0;
//
//        log.info("消息消费完成");
//    }

    /**
     * manual
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = Constants.RETRY_QUEUE)
    public void listener(Message message, Channel channel) throws IOException {

        String messageInfo = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            log.info("接收消息, message: {}, deliveryTag: {}", messageInfo, deliveryTag);

            int num = 1 / 0;

            log.info("消息消费完成");

            channel.basicAck(deliveryTag, false);

        } catch (Exception e) { //此处的异常必须包含 除数为 0 的异常，不然就不会进入到 catch 中，就导致不会执行 basicNack 方法，就无法将消息重新入队列
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
